package front

import (
	"github.com/juju/errors"
	"qihuang/config"
	"qihuang/db/mysql"
	"qihuang/db/redis"
	"qihuang/loger"
	"qihuang/model"
	"qihuang/protocol"
	"strconv"
	"time"
)

type CareParams struct {
	Id         int    `json:"id",gorm:"primary_key;AUTO_INCREMENT"`
	CreateTime string `json:"create_time"`
	ModifyTime string `json:"modify_time"`
	Status     int    `json:"status"`
	Deleted    int    `json:"deleted"`
	DearTag    string `json:"dear_tag"`
	ArticleId  int    `json:"article_id"`
	DearId     int    `json:"dear_id"`
}

type CareDetail struct {
	Id         int    `json:"id",gorm:"primary_key;AUTO_INCREMENT"`
	CreateTime string `json:"create_time"`
	ModifyTime string `json:"modify_time"`
	Status     int    `json:"status"`
	Deleted    int    `json:"deleted"`
	DearTag    string `json:"dear_tag"`
	ArticleId  int    `json:"article_id"`
	DearId     int    `json:"dear_id"`
}
type CareInfo struct {
	Id         int    `json:"id",gorm:"primary_key;AUTO_INCREMENT"`
	CreateTime string `json:"create_time"`
	Title      string `json:"title"`
	Content    string `json:"content"`
	Avatar     string `json:"avatar"`
	Author     string `json:"author"`
	Cover      string `json:"cover"`
	Summary    string `json:"summary"`
	DearName   string `json:"dear_name"`
}

type Cares struct {
}

type CareList struct {
	Total    int        `json:"total"`
	Datalist []CareInfo `json:"datalist"`
}

//添加家庭成员
func (c *Cares) Add(params *CareParams) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "创建失败", Data: ""}
	Care := model.Care{
		Deleted:    0,
		DearId:     params.DearId,
		ArticleId:  params.ArticleId,
		DearTag:    params.DearTag,
		ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		Status:     params.Status,
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
	}

	db := mysql.Default().GetConn()
	defer db.Close()
	// 开始事务
	tx := db.Begin()
	//添加family
	err := db.Model(model.Care{}).Create(&Care).Error
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		tx.Rollback()
		return resp
	}
	//提交事务
	tx.Commit()
	resp.Status = 0
	resp.Msg = "创建成功"
	return resp
}

//更新成员信息
func (c *Cares) Update(id int, params *CareParams) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "更新失败", Data: ""}
	if err := c.deleteCareCache(id); err != nil {
		resp.Msg = "更新失败，请重试！"
		return resp
	}
	//查询ID是否存在
	db := mysql.Default().GetConn()
	defer db.Close()
	count := 0
	if err := db.Model(model.Care{}).Where("id = ?", id).Count(&count).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}

	if count <= 0 {
		resp.Msg = "家庭成员不存在"
		return resp
	}
	articles := model.Care{
		DearId:     params.DearId,
		ArticleId:  params.ArticleId,
		DearTag:    params.DearTag,
		CreateTime: time.Now().Format("2006-01-02 15:04:05"),
		ModifyTime: time.Now().Format("2006-01-02 15:04:05"),
		Status:     params.Status,
	}

	// 开始事务
	tx := db.Begin()
	//添加articles
	err := db.Model(model.Care{}).Where("id = ?", id).Update(&articles).Error
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		tx.Rollback()
		return resp
	}
	//提交事务
	tx.Commit()
	resp.Status = 0
	resp.Msg = "更新失败"
	return resp
}

//分页获取家庭成员列表
func (c *Cares) GetList(familyId int, page int, pageSize int, fields []string) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "获取列表信息失败", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	offset := (page - 1) * pageSize
	careList := &CareList{}
	//familyList := []model.Family{}
	Cares := make([]model.Care, 0)
	total := 0
	var ids []int

	db.Model(&model.Care{}).Count(&total)
	if err := db.Select(fields).Where("family_id=?", familyId).Offset(offset).Limit(pageSize).Order("id desc").Find(&Cares).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	families := Families{}
	familyList := families.GetFamilyList(familyId, 1, 10)
	for i := 0; i < len(Cares); i++ {
		ids = append(ids, Cares[i].ArticleId)
		for k := 0; k < len(familyList); k++ {

		}
	}
	articleSvr := &Articles{}
	Articles := articleSvr.GetListByIdsForMysql(page, pageSize, ids)
	for i := 0; i < len(Cares); i++ {
		var dearName = ""
		for k := 0; k < len(familyList); k++ {
			if Cares[i].DearId == familyList[k].Id {
				dearName = familyList[k].Relation
				break
			}
		}
		for j := 0; j < len(Articles); j++ {
			if Articles[j].Id == Cares[i].ArticleId {
				careInfo := &CareInfo{
					Id:         Articles[j].Id,
					CreateTime: Articles[j].CreateTime,
					Title:      Articles[j].Title,
					Content:    Articles[j].Content,
					Avatar:     Articles[j].Avatar,
					Author:     Articles[j].Author,
					Cover:      Articles[j].Cover,
					Summary:    Articles[j].Summary,
					DearName:   dearName,
				}
				careList.Datalist = append(careList.Datalist, *careInfo)
				break
			}
		}
	}

	careList.Total = len(Articles)
	resp.Status = 0
	resp.Msg = "获取列表成功"
	resp.Data = careList
	return resp
}

//删除文章
func (c *Cares) Delete(id int) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "删除失败", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	if err := c.deleteCareCache(id); err != nil {
		resp.Msg = "删除失败，请重试！"
		return resp
	}
	if err := db.Where("id = ?", id).Delete(&model.Care{}).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	resp.Status = 0
	resp.Msg = "删除成功！"
	return resp
}

//文章详情
func (c *Cares) GetDetail(id int) (resp *protocol.Resp) {
	resp = &protocol.Resp{Status: 1, Msg: "", Data: ""}
	db := mysql.Default().GetConn()
	defer db.Close()
	article := &model.Care{}
	//article_content := &model.ArticlesContents{}

	if err := db.Where("id = ?", id).Find(article).Error; err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		resp.Msg = "系统错误"
		return resp
	}
	CareDetail := &CareDetail{}
	CareDetail.DearTag = article.DearTag
	CareDetail.Id = id
	CareDetail.ArticleId = article.ArticleId
	CareDetail.DearId = article.DearId
	resp.Data = CareDetail
	resp.Status = 0
	return resp
}

func (c *Cares) deleteCareCache(id int) error {
	redisConn := redis.RedisClient.Pool.Get()
	cacheKey := "care_" + config.Configs.RedisCacheVersion + ":" + strconv.Itoa(id)
	if err := redisConn.Err(); err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		return err
	}
	_, err := redisConn.Do("del", cacheKey)
	if err != nil {
		loger.Loger.Error(errors.ErrorStack(errors.Trace(err)))
		return err
	}
	return nil
}
